package mq

import (
	"context"
	"encoding/json"
	"github.com/apache/rocketmq-clients/golang/v5"
	"github.com/apache/rocketmq-clients/golang/v5/credentials"
)

type Publisher interface {
	Publish(ctx context.Context, topic string, data any) error
	Stop() error
}

type publisher struct {
	endpoint  string
	accessKey string
	secretKey string
	producer  golang.Producer
}

func (p *publisher) Stop() error {
	if err := p.producer.GracefulStop(); err != nil {
		return err
	}
	return nil
}

func (p *publisher) Publish(ctx context.Context, topic string, data any) error {
	body, err := json.Marshal(data)
	if err != nil {
		return err
	}
	msg := &golang.Message{
		Topic: topic,
		Body:  body,
	}
	_, err = p.producer.Send(ctx, msg)
	if err != nil {
		return err
	}
	return nil
}

func NewPublisher(endpoint, accessKey, secretKey string) (Publisher, error) {
	p := publisher{
		endpoint:  endpoint,
		accessKey: accessKey,
		secretKey: secretKey,
	}
	producer, err := golang.NewProducer(
		&golang.Config{
			Endpoint: endpoint,
			Credentials: &credentials.SessionCredentials{
				AccessKey:    accessKey,
				AccessSecret: secretKey,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	if err := producer.Start(); err != nil {
		return nil, err
	}
	p.producer = producer
	return &p, nil
}
